package cc.ufinity.networkdiagnose.manager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.app.GlobalApp;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * FTP.
 * @author 张进
 * @email kaixwdi110@163.com
 */
public class SimpleFTP {
    /**
     * 服务器名.
     */
    private String hostName;

    /**
     * 用户名.
     */
    private String userName;

    /**
     * 密码.
     */
    private String password;

    /**
     * 套接字.
     */
    private Socket socket;

    /**
     * 发送命令.
     */
    private BufferedWriter writer;

    /**
     * 接受命令.
     */
    private BufferedReader reader;

    /**
     * 端口号.
     */
    private  int PORT = 21;
    private Socket dataSocket;
    private boolean timeoutOrNot =false;
    
    
    //---------2013-3-11 by svenke
    private int current = 0;
    private Handler storHandler;
    private int totalSize = 0;
    private long totalTime = 0;
    private int curretDownSize = 0;
    private int totalDownSize = 0;
    private long totalDownTime = 0;
    private float avgDownSpeed = 0;
    private boolean istimeOut = false;
    public static String strLog = "ftp-----------------------";//ftp日志信息
    //---------2013-3-11 by svenke

    /**
     * 执行成功.
     */
    private static final boolean DEBUG = true;
    private String delLocalPath;
    public static boolean testing = true;
    public static boolean upTesting = true;
    public static final int CONNECTSUCCEED = 0;
    public static final int UPLOAD = 1;
    public static final int DOWNLOAD = 2;
    public static final int UPOVER = 3;
    public static final int DOWNOVER = 4;
    public static final int TIMEOUTUP = 5;
    public static final int TIMEOUTDOWN = 6;
    public static final int LEVEL = 1024 * 4;
    public static final int LEVELUP = 1024 * 4;
    public static final long freshDelay = 100;
    private static final int timeout = 1000 * 30;
    private static final int upTimeOut = 1000 * 30 * 4;
    private static int arraySize = 20;
	private Handler handler;
    private int fileSize;
    private int fileSizeDown;
    private boolean stop = false;;
    
    
    public boolean isStop() {
		return stop;
	}
	public void setStop(boolean stop) {
		this.stop = stop;
	}
	public int getFileSizeDown() {
		return fileSizeDown;
	}
	public void setFileSizeDown(int fileSizeDown) {
		this.fileSizeDown = fileSizeDown;
	}

	public void setCurrentSpeed(float currentSpeed) {
		this.currentSpeed = currentSpeed;
	}
	public float getCurrentSpeed() {
		return currentSpeed;
	}

	private int completedSize = 0;
	private float currentSpeed = 0;
    private long upTime[] = new long[arraySize];
    private long dwTime[] = new long[arraySize];
    private int upSize[] = new int[arraySize];
    private int dwSize[] = new int[arraySize];
    public double[] upX = new double[arraySize];// 绘制上传报表X轴数据
	public double[] getUpX() {
		return upX;
	}

	public double[] upY = new double[arraySize];// 绘制上传报表Y轴数据
	public double[] getUpY() {
		return upY;
	}

	private double[] dwX = new double[arraySize];
	public double[] getDwX() {
		return dwX;
	}

	private double[] dwY = new double[arraySize];
	public double[] getDwY() {
		return dwY;
	}
	public int getCompletedSize() {
		return completedSize;
	}

	public void setCompletedSize(int completedSize) {
		this.completedSize = completedSize;
	}

	
	public float getAvgDownSpeed() {
		return avgDownSpeed;
	}
	public void setAvgDownSpeed(float avgDownSpeed) {
		this.avgDownSpeed = avgDownSpeed;
	}
	/**
     * 构造函数.
     * @param host hostName 服务器名
     * @param user userName 用户名
     * @param pass password 密码
     */
    public SimpleFTP(String host, int port, String user, String pass, Handler mhandler) {
        this.hostName = host;
        this.PORT = port;
        this.userName = user;
        this.password = pass;
        this.handler = mhandler;
        GlobalApp.simpleFtp = this;
    }

    /**
     * 打开FTP.
     * @throws IOException 
     */
    public void connect() throws IOException {
    	testing = true; 
        if (socket != null) {
        	testing = false;
            throw new IOException("SimpleFTP is already connected. Disconnect first.");
        }
        socket = new Socket();  //创建无连接套接字　
        socket.connect(new InetSocketAddress(hostName, PORT), timeout*2); //设置超时连接
        //socket = new Socket(hostName, PORT);
        //socket.setSoTimeout(timeout);
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String response = readCommand();
        if (!response.startsWith("220 ")) {
        	testing = false;
            throw new IOException("SimpleFTP received an unknown response when connecting to the FTP server: " + response);
        }
        sendCommand("USER " + userName);
        response = readCommand();
        if (!response.startsWith("331 ")) {
        	testing = false;
            throw new IOException("SimpleFTP received an unknown response after sending the user: " + response);
        }
        sendCommand("PASS " + password);
        response = readCommand();
        if (!response.startsWith("230 ")) {
        	testing = false;
            throw new IOException("SimpleFTP was unable to log in with the supplied password: " + response);
        }
    }

    /**
     * 断开FTP.
     * @throws IOException 
     */
    public void disconnect() throws IOException {
    	testing = false;
        try {
            sendCommand("QUIT");
        } finally {
            socket = null;
          //删除下载文件
        	try {
        		int endIndex = delLocalPath.lastIndexOf("/");
        		delLocalPath = delLocalPath.substring(0, endIndex+1);
        		File file = new File(delLocalPath);
            	File[] files = file.listFiles();
            	for(int i=0; i<files.length; i++) {
            		if(!files[i].isDirectory() && files[i].getName().toLowerCase().endsWith(".doc")) {
            			files[i].delete();
            		}
            	}
        	} catch(Exception e) {
        		e.printStackTrace();
//        		System.out.println("删除下载文件出错！！！");
        	}
        }
    }

    /**
     * FTP工作目录.
     * @return 工作目录
     * @throws IOException 
     */
    public String pwd() throws IOException {
        sendCommand("PWD");
        String dir = null;
        String response = readCommand();
        if (response.startsWith("257 ")) {
            int firstQuote = response.indexOf('\"');
            int secondQuote = response.indexOf('\"', firstQuote + 1);
            if (secondQuote > 0) {
                dir = response.substring(firstQuote + 1, secondQuote);
            }
        }
        return dir;
    }

    /**
     * 改变FTP工作目录.
     * @param dir 工作目录
     * @return boolean
     * @throws IOException 
     */
    public boolean cwd(String dir) throws IOException {
        sendCommand("CWD " + dir);
        String response = readCommand();
        return response.startsWith("250 ");
    }

    /**
     * 二进制发送文件.
     * @return boolean
     * @throws IOException 
     */
    private synchronized boolean bin() throws IOException {
        sendCommand("TYPE I");
        String response = readCommand();
        return response.startsWith("200 ");
    }

    /**
     * ASCII发送文件.
     * @return boolean
     * @throws IOException 
     */
    private synchronized boolean ascii() throws IOException {
        sendCommand("TYPE A");
        String response = readCommand();
        return response.startsWith("200 ");
    }

    /**
     * 上传文件.
     * @param file 文件目录
     * @return boolean
     * @throws IOException 
     */
//    public synchronized boolean stor(File file) throws IOException {
//        if (file.isDirectory()) {
//            throw new IOException("SimpleFTP cannot upload a directory.");
//        }
//        String fileName = file.getName();
//        return stor(new FileInputStream(file), fileName);
//    }

    long upStartTime = System.currentTimeMillis();
    
    /**
     * 上传文件.
     * @param localPath 本地路径
     * @param remotePath 远程路径
     * @return boolean 
     * @throws IOException  
     */
    /*/
    public boolean stor(String localPath, String remotePath) throws IOException {
        if (!cwd(remotePath)) {
        	sendCommand("MKD " + remotePath);
            String response = readCommand();
            if (!response.startsWith("257 ")) {
            	throw new IOException("--------------服务端路径不存在且无法创建:" + remotePath);
            }
            		
        }
    	//cwd(remotePath);
    	
        File file = new File(localPath);
        String fileName = file.getName();
        InputStream inputStream = new FileInputStream(file);        
        BufferedInputStream input = new BufferedInputStream(inputStream);
        
        initStorSocket(fileName);
        
        byte[] buffer = new byte[LEVELUP];
        int bytesRead = 0;
        completedSize = 0;
        int count = 1;
        fileSize = input.available();//正确2108416
        Message msg = new Message();
        msg.what = CONNECTSUCCEED;
        msg.arg1 = fileSize;
        handler.sendMessage(msg);
        long start = System.currentTimeMillis();
        upStartTime = start;
        upSize[0] = 0;
    	upTime[0] = start;
    	int trulySize = 0;
    	
    	ThreadTest tt = new ThreadTest(fileName);
	    tt.start();
	    System.out.println("-------------FTP Stor begin write");
	    while ((bytesRead = input.read(buffer)) != -1) {
	    	System.out.println("--------------completedSize:" + completedSize);
	    	try {
	    		//bosDataSocket.write(buffer, 0, bytesRead);
	    		dataSocket.getOutputStream().write(buffer, 0, bytesRead);
	    		trulySize += bytesRead;
	    	} catch (IOException ioe) {
	    		System.out.println("-----------FTP Stor(" + count + ") ERROR:" + ioe.getMessage());
//	    		while (dataSocket == null) {
//	    			try {
//						Thread.sleep(1000 * 2);
//					} catch (InterruptedException e) {}
//	    		}
	    	}
            completedSize += bytesRead;
            upStartTime = System.currentTimeMillis();
            if(completedSize >= fileSize*count/12) {
            	finishFtpPartly(count, trulySize);
            	count ++;
            	trulySize = 0;
            }
        }
	    if (trulySize > 0) {
	    	finishFtpPartly(count, trulySize);
	    }
        
        long time = System.currentTimeMillis() - start;
        try {
			Thread.sleep(100);
		} catch (InterruptedException e) {}
		
		handler.sendEmptyMessage(UPOVER);
        float upSpeed = (((float) fileSize)/1024)*1000/time;
        System.out.println("--------平均上传速度： " + upSpeed);
        
        //bosDataSocket.close();
        input.close();
        if (dataSocket != null)
    		dataSocket.close();
        String response = readCommand();
        return response.startsWith("226 ");
    }
    
    */
    
    /**
     * 上传文件.
     * @param localPath 本地路径
     * @param remotePath 远程路径
     * @return boolean 
     * @throws IOException  
     */
    public boolean stor(String localPath, String remotePath) throws IOException {
		totalTime = 0;
		totalSize = 0;
		if (!cwd(remotePath)) {
			sendCommand("MKD " + remotePath);
			String response = readCommand();
			if (!response.startsWith("257 ")) {
				throw new IOException("--------------服务端路径不存在且无法创建:"
						+ remotePath);
			}else {
				 cwd(remotePath);
			}

		}
		stop = false;
		
		File file = new File(localPath);
		String fileName = file.getName();
		upStartTime = System.currentTimeMillis();
		ThreadTest tt = new ThreadTest(fileName);
		tt.start();
		String response = "";
		BufferedInputStream input = null;
		istimeOut = false;
		try {
			for (int i = 0; i < 10 && !stop ; i++) {// 做10次上传测试;stop检测当前是否为测试中，如果取消测试，stop置为true，退出。
				if (istimeOut) {
					handler.sendEmptyMessage(TIMEOUTUP);
					break;
				}
				InputStream inputStream = new FileInputStream(file);
				input = new BufferedInputStream(inputStream);
				response = "";
				initStorSocket(fileName);

				byte[] buffer = new byte[LEVELUP];
				int bytesRead = 0;
				long start = System.currentTimeMillis();
				int currentSize = 0;
				System.out.println("-------------FTP Stor begin write at" + i);
//				strLog += "-------------FTP Stor begin write at" + i;
				while ((bytesRead = input.read(buffer)) != -1 && !istimeOut ) {
					try {
						// bosDataSocket.write(buffer, 0, bytesRead);
						dataSocket.getOutputStream().write(buffer, 0, bytesRead);
						totalSize += bytesRead;
						currentSize += bytesRead;
					} catch (IOException ioe) {
						System.out.println("-----------FTP Stor(" + i + ") ERROR:"
								+ ioe.getMessage());
					}
				}
				input.close();
				if (dataSocket != null){
					dataSocket.close();
					dataSocket = null;
				}
				response = readCommand();
				System.out.println("i:" + response);

				long time = System.currentTimeMillis() - start;
				totalTime += time;
				upTime[i] = time;// 记录第i次上传花费的时间
				upSize[i] = currentSize; // 记录第i次上传的文件大小
				System.out.println("文件大小："+currentSize);
				System.out.println("花费时间："+time);
				System.out.println("即时速度："+i+":"+currentSize/time);
				inputStream.close();
				updateUpLoad(i);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}
			}
	       
			
			handler.sendEmptyMessage(UPOVER);
	        float upSpeed = (((float) totalSize)/1024)*1000/totalTime;
	        System.out.println("--------平均上传速度： " + upSpeed);
	        
	        //bosDataSocket.close();
	        return response.startsWith("226 ");
		} catch (SocketTimeoutException ste) {
			StringWriter sw = new StringWriter();
			ste.printStackTrace(new PrintWriter(sw, true));
			String str = sw.toString();
			strLog += "SocketTimeoutException:+" + ste.toString() + "\n"+str +"\n";
        	System.out.println("--------stor socket timeout!");
        	handler.sendEmptyMessage(TIMEOUTUP);
        	return false;
        } catch (SocketException ste) {
        	StringWriter sw = new StringWriter();
			ste.printStackTrace(new PrintWriter(sw, true));
			String str = sw.toString();
			strLog += "SocketException:+" + ste.toString() + "\n"+str +"\n";
        	System.out.println("--------stor socket keepalive!");
        	handler.sendEmptyMessage(TIMEOUTUP);
        	return false;
        }catch (IOException e) {
			// TODO: handle exception
        	StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw, true));
			String str = sw.toString();
			strLog += "SocketException:+" + e.toString() + "\n"+str +"\n";
        	System.out.println("--------IOException error!");
        	e.printStackTrace();
        	handler.sendEmptyMessage(TIMEOUTUP);
        	return false;
		} 
        catch (Exception e) {
			// TODO: handle exception
        	e.printStackTrace();
        	StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw, true));
			String str = sw.toString();
			strLog += "SocketException:+" + e.toString() + "\n"+str +"\n";
        	handler.sendEmptyMessage(TIMEOUTUP);
        	return false;
		}finally {
			if (input!=null) {
				 input.close(); 
			}
        	if (dataSocket != null)
        		dataSocket.close();    
        		dataSocket = null;
        }
	
    }
 
	private void initStorSocket(String fileName) throws IOException {
		if (socket == null) {
			connect();
		}
		dataSocket = getConnection();
        sendCommand("STOR " + fileName);
        String response = readCommand();
        if (!response.startsWith("125 ") && !response.startsWith("150 ")) {
            throw new IOException("SimpleFTP was not allowed to send the file: " + response);
        }
        //bosDataSocket = new BufferedOutputStream(dataSocket.getOutputStream());
     }

//	private void finishFtpPartly(int count, int trulySize) throws IOException {
//		System.out.println("------------begin finishFtpPartly(" + count + ")");
//		String response;
//		//bosDataSocket.flush();
////		response = readCommand();
////		if (response.startsWith("226 ")) {
////			upSize[count] = trulySize;
////		} else {
////			upSize[count] = 0;
////		}
//		upSize[count] = trulySize;
//		upTime[count] = upStartTime;            	
//		updateUpLoad(count);
//		System.out.println("------------end finishFtpPartly(" + count + ")");
//	}
	
    /**
     * 上传文件.
     * @param localPath 本地路径
     * @param remotePath 远程路径
     * @return boolean 
     * @throws IOException  
     */
    public boolean stor1(String localPath, String remotePath) throws IOException {
        cwd(remotePath);
        File file = new File(localPath);
        String fileName = file.getName();
        InputStream inputStream = new FileInputStream(file);
        
        BufferedInputStream input = new BufferedInputStream(inputStream);
        dataSocket = getConnection();
        final MyTimer myTimer = new MyTimer();
        try {
        	dataSocket.setSoTimeout(timeout);
	        sendCommand("STOR " + fileName);
	        String response = readCommand();
	        if (!response.startsWith("125 ")) {
	            throw new IOException("SimpleFTP was not allowed to send the file: " + response);
	        }
	        BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream());
	        byte[] buffer = new byte[LEVELUP];
	        int bytesRead = 0;
	        completedSize = 0;
	        int count = 1;
	        fileSize = input.available();//正确2108416
	        Message msg = new Message();
	        msg.what = CONNECTSUCCEED;
	        msg.arg1 = fileSize;
	        handler.sendMessage(msg);
	        long start = System.currentTimeMillis();
	        upStartTime = start;
	        upSize[0] = 0;
        	upTime[0] = start;
        	//myTimer.start(timeout); 
	       ThreadTest tt = new ThreadTest(fileName);
	       tt.start();
	        while (count < 14 && testing && upTesting && (bytesRead = input.read(buffer)) != -1) {
	            output.write(buffer, 0, bytesRead);
	            completedSize += bytesRead;
	            upStartTime = System.currentTimeMillis();
	            if(completedSize >= fileSize*count/13) {
	            	upSize[count] = completedSize;
	            	upTime[count] = upStartTime;
	                //if(count > 2) {
	                    updateUpLoad(count);
	            	//}
	            	count ++;
	            }
	            //myTimer.reStart(timeout);
	        }
	        
	        long time = System.currentTimeMillis() - start;
	        //myTimer.cancel();
	        try {
				Thread.sleep(100);
			} catch (InterruptedException e) {}
			if(!timeoutOrNot)
				handler.sendEmptyMessage(UPOVER);
	        float upSpeed = (((float) fileSize)/1024)*1000/time;
	        System.out.println("--------上传速度： " + upSpeed);

	        output.flush();
	        output.close();
	        response = readCommand();
	        return response.startsWith("226 ");
        } catch (SocketTimeoutException ste) {
        	System.out.println("--------stor socket timeout!");
        	handler.sendEmptyMessage(TIMEOUTUP);
        	return false;
        } catch (SocketException ste) {
        	System.out.println("--------stor socket keepalive!");
        	handler.sendEmptyMessage(TIMEOUTUP);
        	return false;
        } catch (Exception e) {
			// TODO: handle exception
        	e.printStackTrace();
        	handler.sendEmptyMessage(TIMEOUTUP);
        	return false;
		}finally {
	        input.close(); 
        	if (dataSocket != null)
        		dataSocket.close();        	
        }
    }
    class ThreadTest extends Thread{
    	private String fileName;
    	
    	public ThreadTest(String fileName) {
    		this.fileName = fileName;
    	}
    	
		public void run(){
			while(true){
				long time = System.currentTimeMillis() - upStartTime;
				if(time > upTimeOut){
					System.out.println("------------------FTP Stor Timeout");
					istimeOut = true;
					if(dataSocket!=null){
						try {
							dataSocket.close();
						} catch (IOException e) {
							System.out.println("-------------ThreadTest Close dataSocket:" + e.getMessage());
						} finally {
							dataSocket = null;
						}
					}
//					try {
//						String response = SimpleFTP.this.readCommand();
//						System.out.println("------------------FTP Stor response：" + response);
//					} catch (IOException e1) {
//						// TODO Auto-generated catch block
//						System.out.println("------------------FTP Stor response exception：" + e1.getMessage());
//					}
//					try {
//						initStorSocket(this.fileName);
//					} catch (IOException e) {
//						System.out.println("--------------Init Stor Socket Error:" + e.getMessage());
//					}
					//timeoutOrNot = true;
					break;
				}
				try {
					sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					break;
				}
			}
		}
	}

    /**
     * 下载文件.
     * @param fileName 文件名.
     * @param localPath 本地目录.
     * @param remotePath 远程目录.
     * @return boolean
     * @throws IOException 
     */
    public boolean get(String localPath, String remotePath, String fileName) throws IOException {
    	stop = false;
    	delLocalPath = localPath;
        String flow = null;
        Socket dataSocket = getConnection();
        try {
        	dataSocket.setSoTimeout(timeout);
	        cwd(remotePath);
	        sendCommand("RETR " + fileName);
	        String response = readCommand();
	        flow = response;
	        if (!response.startsWith("125 ") && !response.startsWith("150 ")) {
	            throw new IOException("SimpleFTP was not allowed to get the file: " + response);
	        }
	        File file = new File(localPath);
	        try{
	        	file.createNewFile();
	        } catch(Exception e) {}
	        
	        FileOutputStream outputStream = new FileOutputStream(file);
	        BufferedInputStream inputStream = new BufferedInputStream(dataSocket.getInputStream());
	        int n;
	        byte[] buff = new byte[LEVEL];
	        completedSize = 0;
	        /*fileSizeDown = inputStream.available();//获取的值不对192780
	        fileSizeDown = 2290965;//手动设置*/
	        int count = 1;
	        long start = System.currentTimeMillis();
        	dwSize[0] = 0;
        	dwTime[0] = start;
    		System.out.println(fileSizeDown+"==============================filesizedown");
    		//stop为检测当前测试是否取消，stop置为true时，测试取消
	        while (count < 14 && testing && (n = inputStream.read(buff)) != -1 && !stop) { 
	        	
	            outputStream.write(buff, 0, n);
	            
	            completedSize += n;
	            if(completedSize >= fileSizeDown*count/13) {
	            	dwSize[count] = completedSize;
	            	dwTime[count] = System.currentTimeMillis();
	            	if(count > 2) {
	            		updateDownLoad(count);
	            	}
	            	count ++;
	            }
	        }
	        long time = System.currentTimeMillis() - start;
	        try {
				Thread.sleep(100);
			} catch (InterruptedException e) {}
	        FileInputStream inStream = new FileInputStream(new File(localPath));
	        int size = inStream.available();
	        inStream.close();
	        if(testing){
	        	handler.sendEmptyMessage(DOWNOVER);
	        }
	        float downSpeed = (((float) size)/(1024))*1000/time;
	        System.out.println(completedSize + " -------下载速度： " + downSpeed);
	        
	        outputStream.flush(); 
	        outputStream.close();
	
	        response = readCommand();
	        flow += response;
	        System.out.println("flow: " + flow.getBytes().length);
	        return response.startsWith("226 ");
        } catch (SocketTimeoutException ste) {
        	System.out.println("--------get socket timeout!");
        	handler.sendEmptyMessage(TIMEOUTDOWN);
        	return false;
        } finally {
	        dataSocket.close();        	
        }
    }
    /**
     * 下载文件.
     * @param fileName 文件名.
     * @param localPath 本地目录.
     * @param remotePath 远程目录.
     * @return boolean
     * @throws IOException 
     */
	public boolean get1(String localPath, String remotePath, String fileName)
			throws IOException {
		delLocalPath = localPath;
		String flow = null;
		totalDownSize = 0;
		totalDownTime = 0;
		Socket dataSocket = null;
		try {
			cwd(remotePath);
			String response = "";
			for (int i = 0; i < 10; i++) {// 十次下载测试
				dataSocket = getConnection();
				dataSocket.setSoTimeout(timeout);
				sendCommand("RETR " + fileName);
				response = readCommand();
				flow = response;
				if (!response.startsWith("125 ")
						&& !response.startsWith("150 ")) {
					throw new IOException(
							"SimpleFTP was not allowed to get the file: "
									+ response);
				}
				File file = new File(localPath);
				try {
					file.createNewFile();
				} catch (Exception e) {
					System.err.println("Create file error");
				}

				FileOutputStream outputStream = new FileOutputStream(file);
				BufferedInputStream inputStream = new BufferedInputStream(
						dataSocket.getInputStream());
				byte[] buff = new byte[LEVEL];
				int n;
				curretDownSize = 0;
				long start = System.currentTimeMillis();// 开始计时
				System.out.println("beging down file at :" + i);
				while (testing && (n = inputStream.read(buff)) != -1) {

					outputStream.write(buff, 0, n);
					curretDownSize += n;
					totalDownSize += n;
					// if(completedSize >= fileSizeDown*count/13) {
					// dwSize[count] = completedSize;
					// dwTime[count] = System.currentTimeMillis();
					// if(count > 2) {
					// updateDownLoad(count);
					// }
					// count ++;
					// }
				}
				if (dataSocket!=null) {
					dataSocket.close();
					dataSocket = null;
				}
				response = readCommand();
				System.out.println("down respone:" +response);
				long time = System.currentTimeMillis() - start;
				dwSize[i] = curretDownSize;
				dwTime[i] = time;
				totalDownTime += time;
				updateDownLoad(i);
				System.out.println("第"+i+"次下载文件大小："+curretDownSize);
				System.out.println("第"+i+"次下载文件速度："+(float)curretDownSize/1024*1000/time);
				FileInputStream inStream = new FileInputStream(new File(
						localPath));
				int size = inStream.available();
				inStream.close();
				outputStream.flush();
				outputStream.close();
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}
			}//end of FOR

			if (testing) {
				handler.sendEmptyMessage(DOWNOVER);
			}
			if (totalDownTime == 0) {
				avgDownSpeed = 0;
			}else {
				avgDownSpeed = (((float) totalDownSize) / (1024)) * 1000
				/ totalDownTime;
			}
			System.out.println(totalDownSize + " -------下载速度： " + avgDownSpeed);

			return response.startsWith("226 ");
		} catch (SocketTimeoutException ste) {
			System.out.println("--------get socket timeout!");
			handler.sendEmptyMessage(TIMEOUTDOWN);
			return false;
		} finally {
			if (dataSocket!=null) {
				dataSocket.close();
				dataSocket = null;
			}
		}
	}
    /**
     * 大文件下载文件.
     * @param fileName 文件名.
     * @param localPath 本地目录.
     * @param remotePath 远程目录.
     * @return boolean
     * @throws IOException 
     */
    long largeTime;
    public boolean getLarge(String localPath, String remotePath, String fileName) throws IOException {
    	delLocalPath = localPath;
        String flow = null;
        Socket dataSocket = getConnection();
        try {
        	dataSocket.setSoTimeout(timeout);
	        cwd(remotePath);
	        sendCommand("RETR " + fileName);
	        String response = readCommand();
	        flow = response;
	        if (!response.startsWith("125 ") && !response.startsWith("150 ")) {
	            throw new IOException("SimpleFTP was not allowed to get the file: " + response);
	        }
	        File file = new File(localPath);
	        try{
	        	file.createNewFile();
	        } catch(Exception e) {
	        	e.printStackTrace();
	        }
	        
	        FileOutputStream outputStream = new FileOutputStream(file);
	        BufferedInputStream inputStream = new BufferedInputStream(dataSocket.getInputStream());
	        int n;
	        byte[] buff = new byte[LEVEL];
	        completedSize = 0;
	        /*fileSizeDown = inputStream.available();//获取的值不对192780
	        fileSizeDown = 2290965;//手动设置*/
	        long count = 0;
	        int tempSize = 0;
	        long start = System.currentTimeMillis();
        	dwSize[0] = 0;
        	dwTime[0] = start;
    		System.out.println(fileSizeDown+"==============================filesizedown");
    		largeTime = start;
    		int tempCount = 50;
    		switch(GlobalApp.nowNetType) {
				case 1:
					tempCount = 100;
					break;
				case 2:
					tempCount = 25;
					break;
				case 3:
					tempCount = 15;
					break;
				default:
					break;
			}
	        while (testing && (n = inputStream.read(buff)) != -1) {
	        	count ++;
	        	
	        	tempSize += n;
	        	completedSize += n;
	            outputStream.write(buff, 0, n);
				if (count >= tempCount) {
					updateDownLoadLarge(tempSize);
					count = 0;
					tempSize = 0;
				}

	            /*if(completedSize >= fileSizeDown*count/13) {
	            	dwSize[count] = completedSize;
	            	dwTime[count] = System.currentTimeMillis();
	            	if(count > 2) {
	            		updateDownLoad(count);
	            	}
	            	count ++;
	            }*/
	        }
	        long time = System.currentTimeMillis() - start;
	        try {
				Thread.sleep(100);
			} catch (InterruptedException e) {}
	        FileInputStream inStream = new FileInputStream(new File(localPath));
	        int size = inStream.available();
	        inStream.close();
	        if(testing){
	        	handler.sendEmptyMessage(DOWNOVER);
	        }
	        float downSpeed = (((float) size)/(1024))*1000/time;
	        System.out.println(completedSize + " -------下载速度： " + downSpeed);
	        
	        outputStream.flush(); 
	        outputStream.close();
	
	        response = readCommand();
	        flow += response;
	        System.out.println("flow: " + flow.getBytes().length);
	        return response.startsWith("226 ");
        } catch (SocketTimeoutException ste) {
        	System.out.println("--------get socket timeout!");
        	handler.sendEmptyMessage(TIMEOUTDOWN);
        	return false;
        } finally {
	        dataSocket.close();        	
        }
    }
    
    public long[] getDwTime() {
		return dwTime;
	}
	private void updateUpLoad(final int count) {
//    	new Thread() {
//    		public void run() {
//    			long currentTime;
//    			float f;
//    
//				currentTime = upTime[count] - upTime[count - 1];
//				f = ((float)(upSize[count]))/1024*1000/currentTime;
//
//				if(count > 2) {
//					upX[count-3] = count-3;
//					upY[count-3] = f;
//					if(!timeoutOrNot)
//						handler.sendEmptyMessage(UPLOAD);
//				}
//				System.out.println(count +"         " + f);
//    		}
//    	}.start();
		
		new Thread() {
			public void run() {
				long currentTime;
				float f;

				currentTime = upTime[count];
				f = ((float) (upSize[count])) / 1024 * 1000 / currentTime;

				upX[count] = count;
				upY[count] = f;
				if (!timeoutOrNot)
					handler.sendEmptyMessage(UPLOAD);
				System.out.println(count + "         " + f);
			}
		}.start();
    }
    private void updateDownLoad(final int count) {
    	new Thread() {
    		public void run() {
    			long currentTime;
    			float f;

				currentTime = dwTime[count] - dwTime[0];
				f = ((float)(dwSize[count] - dwSize[0]))/1024*1000/currentTime;

				if(count > 3) {
					dwX[count-4] = count-4;
					dwY[count-4] = f;
//					dwY[count-4] = f * 8;//将KB 转化为Kb
					handler.sendEmptyMessage(DOWNLOAD);
				}
				System.out.println(count +"         " + f);
    		}
    	}.start();
//		new Thread() {
//			public void run() {
//				long currentTime;
//				float f;
//
//				currentTime = dwTime[count];
//				f = ((float) (dwSize[count])) / 1024 * 1000 / currentTime;
//
//				dwX[count] = count;
//				dwY[count] = f;
//				handler.sendEmptyMessage(DOWNLOAD);
//				System.out.println(count + "         " + f);
//			}
//		}.start();
    }
    private void updateDownLoadLarge(final int size) {
    	new Thread() {
    		public void run() {
    			long currentTime = System.currentTimeMillis();
				currentSpeed = ((float)size)*1000/1024/(currentTime - largeTime)*8;
				largeTime = currentTime;
//					dwY[count-1] = f * 8;//将KB 转化为Kb
				handler.sendEmptyMessage(DOWNLOAD);
				System.out.println("大文件下载实时速度： " + currentSpeed);
    		}
    	}.start();
    }
    /**
     * 列出FTP目录下文件.
     * @return 文件集合.
     * @throws IOException 
     */
    public synchronized List<String> listFile() throws IOException {
        Socket dataSocket = getConnection();
        sendCommand("LIST ");
        List<String> result = new ArrayList<String>();
        int n;
        byte[] buff = new byte[65536];
        BufferedInputStream inputStream = new BufferedInputStream(dataSocket.getInputStream());
        while ((n = inputStream.read(buff)) > 0) {
            System.out.write(buff, 0, n);
            result.add(new String(buff, 0, n));
        }
        dataSocket.close();
        readCommand();
        readCommand();
        return result;
    }

    /**
     * 构造与服务器交换数据用的Socket
     * 再用PORT命令将端口通知服务器.
     * @return Socket
     * @throws IOException 
     */
    private Socket getConnection() throws IOException {
        sendCommand("PASV");
        String response = readCommand();
        Log.e("resposne", response);
        if (!response.startsWith("227 ")) {
            throw new IOException("SimpleFTP could not request passive mode: " + response);
        }
        String ip = null;
        int port = -1;
        int opening = response.indexOf('(');
        int closeing = response.indexOf(')', opening + 1);
        if (closeing > 0) {
            String dataLink = response.substring(opening + 1, closeing);
            StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
            try {
                ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken();
                port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());
            } catch (Exception e) {
                throw new IOException("SimpleFTP received bad data link information: " + response);
            }
        }
        Log.e("ip", ip);
        Log.e("port", "" + port);
        //Socket dataSocket = new Socket(ip, port);
        Socket dataSocket = new Socket();  //创建无连接套接字　
        dataSocket.connect(new InetSocketAddress(ip, port), timeout); //设置超时连接
        return dataSocket;
    }

    /**
     * 发送命令.
     * @param cmd 命令
     * @throws IOException 
     */
    private void sendCommand(String cmd) throws IOException {
        if (socket == null) {
            throw new IOException("SimpleFTP is not connected.");
        }
        try {
            writer.write(cmd + "\r\n");
            writer.flush();
            if (DEBUG) {
                System.out.println("SEND: " + cmd);
            }
        } catch (IOException e) {
            socket = null;
            throw e;
        } catch (Exception e) {
        	throw new IOException("SimpleFTP is not connected. NullPoint !!!");
        }
    }

    /**
     * 接受命令.
     * @return 命令
     * @throws IOException 
     */
    private String readCommand() throws IOException {
        String cmd = reader.readLine();
        if (DEBUG) {
            System.out.println("RECV: " +cmd);
            strLog += "RECV: " +cmd ;
        }
        return cmd;
    }
}
class MyTimer {
	private Timer timer;
	private TimerTask timerTask;
	
	public MyTimer() {
		timer = new Timer(true);
		timerTask = new TimerTask() {
			@Override
			public void run() {
				SimpleFTP.upTesting = false;
				System.out.println("-------------- SimpleFTP 上传超时 ！");
			}
		};
	}
	public TimerTask getTimerTask(){
		timerTask.cancel();
		timerTask = null;
		timerTask = new TimerTask() {
			@Override
			public void run() {
				SimpleFTP.upTesting = false;
				System.out.println("-------------- SimpleFTP 上传超时 ！");
			}
		};
		return timerTask;
	}
	public void start(long delay) {
		timer.schedule(timerTask, delay);
	}
	public void reStart(long delay) {
		getTimerTask();
		timer.schedule(timerTask, delay);
	}
	public void cancel() {
		timer.cancel();
	}
}

